package com.example.uilearning;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;

public class ImageViewActivity extends Activity {

	private Button but1, but2, but3;
	private ImageView view1, view2;
	private int[] pics = new int[] { R.drawable.pic1, R.drawable.pic2,
			R.drawable.pic3, R.drawable.pic4, R.drawable.pic5 };
	private int currentPic = 0;
	private int alpha = 255;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image_view);
		but1 = (Button) findViewById(R.id.button1);
		but2 = (Button) findViewById(R.id.button2);
		but3 = (Button) findViewById(R.id.button3);
		view1 = (ImageView) findViewById(R.id.image1);
		view2 = (ImageView) findViewById(R.id.image2);
		but3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				view1.setImageResource(pics[++currentPic % pics.length]);
			}
		});
		// 改变图片透明度
		OnClickListener onClickListener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (v.getId() == R.id.button1) {
					alpha = alpha + 20;
				} else {
					alpha = alpha - 20;
				}
				if (alpha > 255 || alpha < 0) {
					alpha = 255;
				}
				view1.setAlpha(alpha);
			}
		};
		but1.setOnClickListener(onClickListener);
		but2.setOnClickListener(onClickListener);
		view1.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				BitmapDrawable bitmapDrawable = (BitmapDrawable) view1
						.getDrawable();
				Bitmap bitMap = bitmapDrawable.getBitmap();
				// 缩放比
				double scale = bitMap.getWidth() / 320;
				int x = (int) (event.getX() * scale);
				int y = (int) (event.getY() * scale);
				if (x + 120 > bitMap.getWidth()) {
					x = bitMap.getWidth() - 120;
				}
				;
				if (y + 120 > bitMap.getHeight()) {
					y = bitMap.getHeight() - 120;
				}
				;
				// 显示图片指定区域
				view2.setImageBitmap(Bitmap
						.createBitmap(bitMap, x, y, 120, 120));
				view2.setAlpha(alpha);
				return false;
			}
		});
	}
}
